package com.xsy.de.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xsy.de.entity.ResultMsg;
import com.xsy.de.entity.User;
import com.xsy.de.service.UserService;
import com.xsy.de.service.impl.SmsServiceImpl;
import com.xsy.de.util.EhcacheUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    private final static Logger log = LogManager.getLogger(LoginController.class);

    private final UserService userService;

    private final SmsServiceImpl smsService;

    public LoginController(UserService userService, SmsServiceImpl smsService) {
        this.userService = userService;
        this.smsService = smsService;
    }

    @RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
    public String login(HttpServletRequest request) {
        try {
            String login = request.getSession().getAttribute("login").toString();
            if ("Y".equals(login)){
                return "index";
            }
            return "loginV2";
        }catch (Exception e){
            return "loginV2";
        }

    }

    @GetMapping(value = "/login")
    public String toLogin() {

        return "loginV2";
    }

    @GetMapping(value = "/loginf")
    public String toLoginf() {

        return "loginV2";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request, HttpSession session) {
        session.setAttribute("login","N");
        session.setAttribute("user", null);
        return "redirect:/login";
    }

    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request, HttpSession session) {
        try {
            String login = request.getSession().getAttribute("login").toString();
            if ("Y".equals(login)){
                return "index";
            }
            return "loginV2";
        }catch (Exception e){
            return "loginV2";
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public String toLoginPage(HttpServletRequest request, HttpSession session, ModelMap map){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_NAME", request.getParameter("username"));
        queryWrapper.eq("USER_PWD", request.getParameter("userpwd"));
        List<User> users = userService.selectList(queryWrapper);
        if (users.size() > 0){
            session.setAttribute("login","Y");
            session.setAttribute("user", users.get(0));
            return "success";
        }else {
            return "fail";
        }
    }

    @RequestMapping(value = "/reg")
    public String userReg(HttpServletRequest request, HttpSession session) {

        return "reg";
    }

    @PostMapping(value = "/sendCode")
    @ResponseBody
    public String sendCode(String username, HttpServletRequest request, HttpSession session) {
        String code = createRandomNum(6);
        ResultMsg resultMsg = smsService.sndSmsCode(username,code);
        if ("0".equals(resultMsg.getRtncode())){
            EhcacheUtil.put("SMS",username + "Code",code);

        }
        return JSONObject.toJSONString(resultMsg);

    }

    private static String createRandomNum(int num){
        StringBuilder randomNumStr = new StringBuilder();
        for(int i = 0; i < num;i ++){
            int randomNum = (int)(Math.random() * 10);
            randomNumStr.append(randomNum);
        }
        return randomNumStr.toString();
    }
}
